import json

from django.contrib.auth import login, logout, authenticate
from django.db import DatabaseError
from django.http import HttpResponse, JsonResponse, HttpResponseForbidden
from django.shortcuts import render, redirect
from django.views.generic.base import View
from django.urls import reverse
import re




# Create your views here.
from mangguo_pro.utils.error import Fobbiden
from .models import User


class RegisterView(View):
    def get(self,request):
        return render(request,'userapp/register.html')
    def post(self,request):
        #获取参数
        username=request.POST.get('username','')
        phone=request.POST.get('phone','')
        password=request.POST.get('password', '')


        #校验参数

        if not all([username,password,phone]):
            raise Fobbiden('缺少必要参数')
        if not re.match(r'^[A-Za-z][A-Za-z0-9_]{4,7}$',username):
            raise Fobbiden('用户名格式错误')
        if not re.match(r'^[A-Za-z0-9]{3,8}$',password):
            raise Fobbiden('密码格式错误')
        if not re.match(r'1[3589]\d{9}$',phone):
            raise Fobbiden('请输入正确的手机号')

        #导入数据库
        try:
            User.objects.create_user(username=username,password=password,phone=phone)

        except DatabaseError:
            return render(request,'userapp/register.html',{'reg_error_msg':'注册失败！'})

        #状态保持
        login(request,user=username)



        #返回数据
        return redirect(reverse('newsapp:index'))
class Username(View):
    def get(self,request,username):
       count= User.objects.filter(username=username).count()
       return JsonResponse({'code':200,'msg':'OK','count':count  })


class LogoutView(View):
    def get(self,request):
         logout(request)
         return redirect(reverse('newsapp:index'))
class PhoneCount(View):
    def get(self,request,phone):
       count= User.objects.filter(phone=phone).count()
       return  JsonResponse({'code':200,'msg':'OK','count':count})


class LoginView(View):

    def get(self,request):
     #显示登陆首页

        return render(request,'userapp/login.html')


    def post(self,request):
        '''

         Handling login request   处理登录请求

        :param request:
        :return:
        '''

        #receive  parameter  接受请求参数

        username=request.POST.get('username','')
        password = request.POST.get('password', '')
        remember = request.POST.get('remember', '')


        # check  parameter   校验请求参数
        if not all([username,password,remember]):
            return HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^[0-9a-zA-Z]{3,8}$',username):
            return HttpResponseForbidden('请输入3-8位字符的用户名')

        if not re.match(r'^[0-9a-zA-Z]{3,8}$', password):
            return HttpResponseForbidden('请输入3-8位字符的密码')


        # Check whether the parameters is correct   判断请求参数是否正确
        user=authenticate(username=username,password=password)
        if user is None:
            return render(request,'userapp/login.html',{'login_error':'用户名或密码错误'})


        #keep status  状态保持
        login(request,user)
        if remember!='yes':
            #关闭浏览器失效
            request.session.set_expiry(0)

        else:
            #14天有效期
            request.session.set_expiry(None)




        #response results   响应结果

        return redirect(reverse('newsapp:index'))

class EmailView(View):

    def post(self,request):
        #获取参数
        gain_arg= request.body.decode()
        #校验参数
        if gain_arg is None:
            return JsonResponse({'code':400,'errormsg':'没有获取到参数'})
        dict_gain_arg=json.loads(gain_arg)
        #保存参数
        count= User.objects.filter(id=dict_gain_arg['userid']).update(email=dict_gain_arg['email'])
        if count>0:
            return JsonResponse({'code':200,'errormsg':'OK'})
        #返回响应
        return JsonResponse({'code':500,'errormsg':'邮箱保存失败'})


